package com.ys.controller.web.sys;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ys.entity.sys.SysCol;
import com.ys.entity.sys.SysMenu;
import com.ys.enume.sys.SysMenuEnum;
import com.ys.service.sys.SysMenuService;
import com.ys.vo.W;

import lombok.AllArgsConstructor;
import lombok.Data;

@Controller
@RequestMapping("/web/sys/sysMenu")
public class WebSysMenuController {
	
	@Autowired
	private SysMenuService sysMenuService;
	
	/**
	 * 新增一级菜单
	 */
	@GetMapping("/toAddOneMenu")
	public String toAddOneMenu(Model model){
		return "sys/sysMenu/toAddOneMenu";
	}
	
	/**
	 * 新增二级菜单
	 */
	@GetMapping("/toAddTwoMenu")
	public String toAddTwoMenu(Model model, Long pid){
		
		return sysMenuService.toAddTwoMenu(model, pid);
	}
	
	
	/*
	 * 新增
	 * 跳转新增二级菜单弹出层
	 */
	@GetMapping("/toAddThreeMenu")
	public String toAddThreeMenu(Model model, HttpServletRequest request, HttpServletResponse response, 
			Long pid){
		
		return sysMenuService.toAddThreeMenu(model, pid);
	}
	
	/*
	 * 调整顺序
	 */
	@GetMapping("/toResort")
	public String toResort(Model model, HttpServletRequest request, HttpServletResponse response, 
			Integer type, // 类型，1模块的子菜单2一级菜单的子菜单
			Long pid){
		
		return sysMenuService.toResort(model, pid);
	}
	
	/**
	 * 跳转菜单初始化弹出层
	 */
	@GetMapping("/toThreeMenuInit")
	public String toThreeMenuInit(Model model, HttpServletRequest request, HttpServletResponse response,
			Long menuId, Integer tabIndex){
		
		tabIndex = tabIndex == null ? 1 : tabIndex;
		
		if (menuId == null) {
			return W.error(model, "菜单ID不能为空");
		}
		
		SysMenu sysMenu = new SysMenu().setId(menuId).queryFirst();
		if (sysMenu == null) {
			return W.error(model, "菜单不存在");
		} else if (sysMenu.getLev() != SysMenuEnum.Lev.THREE.value) {
			return W.error(model, "非第三级菜单无法初始化");
		}
		
		// ID-sys_col的MAP
		Map<Long, SysCol> ID_SYS_COL_MAP = new HashMap<Long, SysCol>();
		// 字段列表（总）
		List<SysCol> listSysCol = new SysCol().setMenuId(menuId).setOrderby("A.id asc").queryList();
		for(SysCol sysCol : listSysCol) {
			ID_SYS_COL_MAP.put(sysCol.getId(), sysCol);
		}
		
		TwoMenuInitDto dto = new TwoMenuInitDto(tabIndex, menuId);
		model.addAttribute("dto", dto);
		
		return "sys/sysMenu/toThreeMenuInit";
	}
	@Data
	@AllArgsConstructor
	private static class TwoMenuInitDto{
		private Integer tabIndex;
		private Long menuId; // 菜单ID
	}

	/*
	 * 编辑菜单（基础信息）
	 */
	@GetMapping("/toEditSysMenu")
	public String toEditSysMenu(Model model, HttpServletRequest request, HttpServletResponse response, 
			Long id, Integer tabIndex){
		return sysMenuService.toEditSysMenu(model, id, tabIndex);
	}
}
